package com.zhang.hadoop.netty.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author zhang yufei
 * @date 2022/1/12 2:27 下午
 **/
public class GroupChatClient {

    private final String HOST = "127.0.0.1";

    private final int PORT = 6667;

    private Selector selector;

    private SocketChannel socketChannel;

    private String username;

    //构造器,完成初始化工作
    public GroupChatClient() {
        try {
            selector = Selector.open();
            //连接服务器
            socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
            //设置非阻塞
            socketChannel.configureBlocking(false);
            //将 channel 注册到 selector
            socketChannel.register(selector, SelectionKey.OP_READ);
            //得到 username
            username = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println(username+" is ok");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //像服务器发送消息
    public void  sendInfo(String info){
        info= username+" 说:"+info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //读取服务端返回的消息
    public void readInfo(){
        try {
            int readChannels=selector.select();
            if (readChannels > 0) {//有可用的通道
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key=iterator.next();
                    if (key.isReadable()) {
                        //得到相关通道
                        SocketChannel channel=(SocketChannel) key.channel();
                        //得到一个 buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        //读取
                        channel.read(buffer);
                        //把读取的缓冲数据转成字符串
                        String msg=new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                    //删除当前的 selectionKey 防止重复操作
                    iterator.remove();
                }
            }else {
                //System.out.println("没有可以用的通道");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        //启动客户端
        GroupChatClient chatClient=new GroupChatClient();
        //启动一个线程,每隔三秒从服务器端读取数据
        new Thread(){
            public void run(){
                while (true){
                    chatClient.readInfo();
                    try {
                        Thread.currentThread().sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        //发送数据给服务器
        Scanner scanner=new Scanner(System.in);
        while (scanner.hasNextLine()){
            String s=scanner.nextLine();
            chatClient.sendInfo(s);
        }
    }
}
